package com.ktmall.service.impl;

import com.ktmall.mapper.*;
import com.ktmall.pojo.*;
import com.ktmall.service.GoodsItemService;
import com.ktmall.vo.CartItemVo;
import com.ktmall.vo.PreOrder;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 猜你喜欢和商品分类相关Service实现类
 */
@Service
public class GoodsItemServiceImpl implements GoodsItemService {
    @Autowired
    private GoodsItemMapper goodsItemMapper;

    @Override
    public List<GoodsItem> getGoodsListPage(Integer pageNo, Integer pageSize) {
        Integer currPageNo = (pageNo - 1) * pageSize;
        return goodsItemMapper.getGoodsListPage(currPageNo, pageSize);
    }

    @Override
    public int count() {
        return goodsItemMapper.count();
    }

    @Override
    public List<GoodsItem> getGoodsByCategoryId(Integer categoryId) {
        return goodsItemMapper.getGoodsByCategoryId(categoryId);
    }

    @Autowired
    private SkuItemMapper skuItemMapper;
    @Autowired
    private AttrValuesMapper attrValuesMapper;
    @Autowired
    private AttrItemMapper attrItemMapper;
    @Autowired
    private BrandItemMapper brandItemMapper;
    @Autowired
    private CategoryItemMapper categoryItemMapper;
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 通过商品id查询商品的详情信息(包括详情的SKU列表、商品的规格属性等信息)
     *
     * @param id 商品id
     * @return 返回查询到的商品详情信息
     */
    @Override
    public GoodsItem findById(Integer id) {
        //1.通过商品id查询商品的基本信息
        GoodsItem goods = goodsItemMapper.findById(id);
        goods.setPicturesArr(goods.getDetailsPictures().split(","));
        goods.setMainImg(goods.getMainPictures().split(","));
        if (goods == null) return null;
        //2.查询该商品的规格属性值列表
        List<AttrValues> attrVals = attrValuesMapper.getAttrVals(goods.getId());
        //3.规格属性值列表加载出所对应的规格属性列表。比如属性值是：黄色、白色。属性是颜色
        //3.1根据商品id查询该商品的所有属性列表
        List<AttrItem> goodsAttr = attrItemMapper.findAttrByGoodsId(goods.getId());
        //3.2遍历规格属性列表，查询出属性下的属性值列表
        goodsAttr = goodsAttr.stream().map(attr -> {
            //3.3查询出当前属性下的属性值列表
            List<AttrValues> avList = attrVals.stream().filter(gav -> {
                //过滤条件：属性值对象中的属性id == 属性对象的id
                return gav.getAttrId() == attr.getId();
            }).collect(Collectors.toList());
            //3.4再将属性值列表添加在attr对象的values属性中
            attr.setValues(avList);
            //3.5最后将带有属性值列表的属性对象进行返回
            return attr;
        }).collect(Collectors.toList());
        //4.根据品牌id查询品牌详情信息
        BrandItem brandItem = brandItemMapper.findById(goods.getBrandId());
        //5.根据类别id查询类别详情信息
        CategoryItem categories = categoryItemMapper.findById(goods.getCategoryId());
        //6.查询该商品SKU列表
        List<SkuItem> skuList = skuItemMapper.findByGoodsId(goods.getId());
        //6.1遍历SKU列表，目的是为每个SKU获取specs规格属性列表
        skuList.stream().map(skuItem -> {
            //6.2查询每个SKU的属性值列表
            List<AttrValues> skuAttrVals = attrValuesMapper.getSkuAttrVals(skuItem.getStockSku());
            //6.3查询每个SKU的属性列表
            List<AttrItem> attrs = attrItemMapper.findAttrByStockSku(skuItem.getStockSku());
            //6.4遍历SKU的规格属性列表，查询出每个属性下的属性值列表
            attrs = attrs.stream().map(attr -> {
                //6.5查询出当前属性下的属性值列表
                List<AttrValues> aVs = skuAttrVals.stream().filter(attrV -> {
                    //过滤条件：属性值对象的属性id == 属性对象的id
                    return attrV.getAttrId() == attr.getId();
                }).collect(Collectors.toList());
                //将过滤出来的属性值列表aVs赋值给attr属性对象的values
                attr.setValues(aVs);
                return attr;
            }).collect(Collectors.toList());
            //将属性列表attrs赋值给skuItem对象的specs集合
            skuItem.setSpecs(attrs);
            return skuItem;
        }).collect(Collectors.toList());

        //7.将sku列表、规格属性列表赋值给商品对象
        goods.setSkus(skuList); //sku列表
        goods.setSpecs(goodsAttr);  //规格属性列表
        goods.setBrandItem(brandItem); //商品品牌
        goods.setCategories(categories); //商品类别
        return goods;
    }

    @Override
    public PreOrder buyNow(Integer userId, Integer skuId, Integer goodsCount) {
        // 获取默认地址
        AddressParams defaultAddress = addressMapper.getDefaultAddress(userId);
        //获取商品基本信息
        SkuItem skuItem = skuItemMapper.findById(skuId);
        GoodsItem goodsItem = goodsItemMapper.findById(skuItem.getGoodsId());
        CartItemVo cartItemVo = new CartItemVo();
        cartItemVo.setGoodsId(goodsItem.getId());
        cartItemVo.setSkuId(skuItem.getId());
        cartItemVo.setName(goodsItem.getGoodsName());
        cartItemVo.setPicture(skuItem.getPicture());
        cartItemVo.setCount(goodsCount);
        cartItemVo.setPrice(skuItem.getPrice());
        cartItemVo.setNowPrice( skuItem.getPrice().multiply(new BigDecimal("0.9")).setScale(2));
        cartItemVo.setStock(Integer.valueOf(skuItem.getInventory()+""));
        // 获取商品规格属性值
        List<AttrValues> skuAttrVals = attrValuesMapper.getSkuAttrVals(skuItem.getStockSku());
        // 获取商品规格属性列表
        List<AttrItem> attrs = attrItemMapper.findAttrByStockSku(skuItem.getStockSku());
        //查询每个SKU的属性下的属性值列表
        attrs = attrs.stream().peek(attr -> {
            //5.1查询出当前属性下的属性值列表
            List<AttrValues> aVs = skuAttrVals.stream().filter(attrV -> {
                return attrV.getAttrId().equals(attr.getId()); //过滤条件：属性值对象的属性id==属性对象的id
            }).collect(Collectors.toList());
            attr.setValues(aVs); //将过滤出来的属性值列表aVs赋值给attr属性对象的values
        }).toList();
        skuItem.setSpecs(attrs);    //将属性列表attrs赋值给skuItem对象的specs集合。此时的attrs中包含属性值列表
        // 拼接商品规格属性值
        String attrsText = skuItem.getSpecs().stream()
                .flatMap(spec -> spec.getValues().stream())
                .map(AttrValues::getName)
                .collect(Collectors.joining(" "));
        cartItemVo.setAttrsText(attrsText);
        List<CartItemVo> list = new ArrayList<>();
        list.add(cartItemVo);
        PreOrder preOrder = new PreOrder(defaultAddress,list);
        return preOrder;
    }
}
